package com.sea.example.utils;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: HttpClientUtil
 * @Description: http工具类
 * @author ly
 * @date 2018年12月28日 下午2:53:22
 * @version 1.0
 */
public class HttpClientUtil {

	/**
	 * @Title: getRequest
	 * @Description: get请求
	 * @return String 返回类型
	 * @date 2018年12月28日 下午2:53:43
	 * @param url
	 * @param params
	 * @return
	 */
	public static String getRequest(String url, Map<String, String> params) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (params != null) {
				for (String key : params.keySet()) {
					builder.addParameter(key, params.get(key));
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static void downloadFile(String url, Map<String, String> params, String filePath) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (params != null) {
				for (String key : params.keySet()) {
					builder.addParameter(key, params.get(key));
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 获取返回的实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// 读取文件流
				InputStream inputStream = entity.getContent();
				try (FileOutputStream fos = new FileOutputStream(new File(filePath))) {
					byte[] buffer = new byte[1024];
					int len;
					while ((len = inputStream.read(buffer)) != -1) {
						fos.write(buffer, 0, len);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @Title: postRequest
	 * @Description: post请求
	 * @return String 返回类型
	 * @date 2018年12月28日 下午2:54:13
	 * @param url
	 * @param params
	 * @return
	 */
	public static String postRequest(String url, Map<String, String> params) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (params != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (String key : params.keySet()) {
					paramList.add(new BasicNameValuePair(key, params.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	/**
	 * @Title: postRequest
	 * @Description: post请求
	 * @return String 返回类型
	 * @date 2018年12月28日 下午2:54:13
	 * @param url
	 * @param params
	 * @return
	 */
	public static String postRequest(String url, Map<Object,Object> params,Map<Object, Object> headers) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			//添加请求头
			if (null != headers){
				headers.forEach((key, value) -> httpPost.addHeader(key.toString(),value.toString()));
			}
			// 创建参数列表
			if (params != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Object key : params.keySet()) {
					paramList.add(new BasicNameValuePair(key.toString(), params.get(key).toString()));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	/**
	 * @Title: postRequestJson
	 * @Description: postJson请求
	 * @return String 返回类型
	 * @date 2018年12月28日 下午2:55:15
	 * @param url
	 * @param json
	 * @return
	 */
	public static String postRequestJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			if(StringUtils.isNotBlank(json)){
				StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}


	/**
	 * @Title: postRequestJson
	 * @Description: postJson请求
	 * @return String 返回类型
	 * @date 2018年12月28日 下午2:55:15
	 * @param url
	 * @param json
	 * @return
	 */
	public static String postRequestJson(String url, String json,Map<String,String> header) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			if (MapUtils.isNotEmpty(header)){
				header.forEach(httpPost::addHeader);
			}
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}


	private static final void closeQuietly(Closeable obj) {
		if (obj == null) {
			return;
		}
		try {
			obj.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		} finally {
			obj = null;
		}
	}

	/**
	 * HttpGet
	 *
	 * @param url
	 * @return
	 */
	public static String doGetQuery(CloseableHttpClient httpclient, String url) {

		StringBuilder resultXml = new StringBuilder();
		try {
			doGet(url, resultXml, httpclient);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (httpclient != null) {

					httpclient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultXml.toString();
	}

	/**
	 * HttpGet
	 *
	 * @param url
	 * @param resultXml
	 * @param httpclient
	 * @throws IOException
	 */
	public static void doGet(String url, StringBuilder resultXml, CloseableHttpClient httpclient) throws IOException {

		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = httpclient.execute(httpGet);
		try {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
				String text = "";
				while ((text = bufferedReader.readLine()) != null) {
					resultXml.append(text);
				}
			}
			EntityUtils.consume(entity);
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	public static void doClose(CloseableHttpClient httpClient) {

		if (httpClient != null) {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
